package com.opennews.openplatform

import grails.compiler.GrailsCompileStatic
import groovy.transform.CompileStatic
import org.springframework.security.crypto.factory.PasswordEncoderFactories

/**
 * https://github.com/dspies/grails-3-with-security
 */
@GrailsCompileStatic
class User {
	String id
	AccountGroup accountGroup
	String username
	String password
	String fullName
	String avatarFilename
	String description
	Integer gender
	Integer authFailedAttempt = 0
	boolean enabled = true
	boolean accountExpired = false
	boolean accountLocked = false
	boolean passwordExpired = false
	Date dateCreated
	Date lastUpdated

	static constraints = {
		accountGroup nullable: false
		username nullable: false, blank: false, maxSize: 50, unique: true
		password nullable: false, blank: false, maxSize: 100, password: true
		fullName nullable: false, blank: false, maxSize: 50
		avatarFilename nullable: true, blank: true, maxSize: 200
		description nullable: true, blank: true, maxSize: 200
		gender nullable: true
	}

	static mapping = {
		password column: '`password`'
	}

	void beforeInsert() {
		encodePassword()
	}

	void beforeUpdate() {
		if (isDirty("password")) {
			encodePassword()
		}
	}

	protected void encodePassword() {
		password = PasswordEncoderFactories.createDelegatingPasswordEncoder().encode(password)
	}
}